<script lang="ts" setup>
import { ref, reactive, toRefs, watch } from "vue" // vue
import { FormInstance } from "element-plus" // elment
import { Search, Refresh, Download } from "@element-plus/icons-vue" // 按钮图标
import { getstockOrderDataApi, downLoadOrder } from "@/api/stock-operation/order" // 接口
import { usePagination } from "@/hooks/usePagination" // 分页器
import { getComboDataSApi } from "@/api/stock-operation/comboSet" // 存量套餐
import { formatDateTime } from "@/utils" // 时间转换
import { shortcuts } from "@/utils/dateSet"
const defaultTime1: [Date, Date] = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 0)]
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination() // 分页器
// 表单
const data = reactive<any>({
  formData: {},
  searchData: {
    id: undefined, // 订单id
    superId: undefined, // 订单上级id
    source: undefined, // 订单来源
    superName: undefined, // 上级名
    phone: undefined, // 手机号
    stockId: undefined, // 存量套餐
    type: undefined, // 类型
    reId: undefined, // 推荐人
    time: "",
    state: undefined // 订单状态
  } // 表单验证
  // rules: {
  //   name: [
  //     {
  //       required: true,
  //       message: "请输入一级分类",
  //       trigger: "blur"
  //     }
  //   ]
  // }
})
const { searchData } = toRefs(data)

// #region 查
const tableData = ref<any>([])
function tablelist() {
  if (!searchData.value.time) {
    searchData.value.time = []
  }
  getstockOrderDataApi({
    ...searchData.value,
    page: paginationData.currentPage,
    size: paginationData.pageSize,
    start: new Date(searchData.value.time[0]).getTime() || "",
    end: new Date(searchData.value.time[1]).getTime() || ""
  })
    .then((res: any) => {
      tableData.value = res.data.list
      paginationData.total = res.data.total
    })
    .catch(() => {
      tableData.value = []
    })
}
tablelist()

// 存量套餐
const comboList = ref<any>([])
getComboDataSApi().then((res) => {
  comboList.value = res.data
  console.log(res.data.list, "8888")
})
const formatterCombo = (row: any, column: any, celValue: any) => {
  comboList.value.filter((item: any) => {
    if (item.id == row.stockId) {
      celValue = item.name
    }
  })
  return celValue
}
// #endregion

// #region 搜索内容
const searchFormRef = ref<FormInstance | null>(null)
// 搜索
function handleSearch() {
  tablelist()
}
// 重置
function resetSearch() {
  searchFormRef.value?.resetFields()
  handleSearch()
}
// #endregion

// #region 添加和修改框
// const dialogVisible = ref(false)
// const formRef = ref<FormInstance | null>(null)
// const ids = ref(undefined) // 判断修改还是增加

// 查看详情
// const handleUpdate = (row: any) => {
//   console.log(row, 88)
//   ids.value = row.id
//   dialogVisible.value = true
//   formData.value = JSON.parse(JSON.stringify(row)) // 赋值需要深拷贝
// }

// 清空form框
// const clearValidate = () => {
//   formRef.value?.resetFields()
// }

// 清空对话框
// const resetForm = () => {
//   ids.value = undefined
//   clearValidate()
//   formData.value = {}
// }

// #endregion

// #region 下载
const downLoad = () => {
  if (!searchData.value.time) {
    searchData.value.time = []
  }
  downLoadOrder({
    ...searchData.value,
    start: new Date(searchData.value.time[0]).getTime() || "",
    end: new Date(searchData.value.time[1]).getTime() || ""
  }).then((res: any) => {
    const blob = new Blob([res.data], {
      type: "application/xlsx;charset=utf-8"
    })
    const downloadElement = document.createElement("a")
    const href = window.URL.createObjectURL(blob)
    downloadElement.href = href
    downloadElement.download = "存量订单.xlsx"
    document.body.appendChild(downloadElement)
    downloadElement.click()
    window.URL.revokeObjectURL(href)
  })
}
// #endregion

// #region 监听代理账号缓存
import { useReStore } from "@/store/modules/reId"
const reStore = useReStore()
reStore.getReFn()
const reList = ref<any>([])
watch(
  [() => reStore.reListStore],
  (newValue) => {
    reList.value = newValue.flat()
  },
  {
    immediate: true
  }
)
// #endregion

/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], tablelist, { immediate: true })
</script>

<template>
  <div class="app-container">
    <el-card>
      <el-row justify="center" align="middle">
        <el-col>
          <el-form ref="searchFormRef" :inline="true" :model="searchData">
            <el-form-item prop="time" label="订单日期">
              <el-date-picker
                v-model="searchData.time"
                type="datetimerange"
                range-separator="到"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                :shortcuts="shortcuts"
                :default-time="defaultTime1"
              />
            </el-form-item>
            <el-form-item prop="id" label="订单id">
              <el-input v-model.trim="searchData.id" clearable placeholder="请输入" />
            </el-form-item>
            <el-form-item prop="superId" label="订单上级id">
              <el-input v-model.trim="searchData.superId" clearable placeholder="请输入" />
            </el-form-item>
            <el-form-item prop="source" label="订单来源">
              <el-input v-model.trim="searchData.source" clearable placeholder="请输入" />
            </el-form-item>
            <el-form-item prop="superName" label="上级名">
              <el-input v-model.trim="searchData.superName" clearable placeholder="请输入" />
            </el-form-item>
            <el-form-item prop="phone" label="手机号">
              <el-input v-model.trim="searchData.phone" clearable placeholder="请输入" />
            </el-form-item>
            <el-form-item prop="stockId" label="存量套餐">
              <el-select v-model="searchData.stockId" filterable clearable placeholder="请选择">
                <el-option
                  :class="item.state == '下架' ? 'Xjstate' : ''"
                  v-for="item in comboList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item prop="type" label="类型">
              <el-select v-model.trim="searchData.type" clearable placeholder="请选择">
                <el-option :key="1" label="活动" value="活动" />
                <el-option :key="2" label="流量包" value="流量包" />
              </el-select>
            </el-form-item>
            <el-form-item prop="state" label="订单状态">
              <el-select v-model.trim="searchData.state" clearable placeholder="请选择">
                <el-option :key="1" label="处理中" value="200" />
                <el-option :key="2" label="受理成功" value="100" />
                <el-option :key="3" label="受理失败" value="400" />
              </el-select>
            </el-form-item>
            <el-form-item prop="reId" label="推荐人">
              <el-select v-model="searchData.reId" clearable filterable placeholder="请选推荐人" style="width: 240px">
                <el-option v-for="item in reList" :key="item.user_id" :label="item.user_name" :value="item.user_id" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
              <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
      <div>
        <el-tooltip content="下载">
          <el-button type="primary" :icon="Download" circle @click="downLoad" />
        </el-tooltip>
      </div>
    </el-card>

    <el-card style="margin-top: 20px">
      <el-table :data="tableData" style="width: 100%" border>
        <el-table-column prop="id" label="订单id" align="center" />
        <el-table-column prop="createTime" label="创建时间" align="center">
          <template #default="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" align="center">
          <template #default="scope">
            {{ formatDateTime(scope.row.updateTime) }}
          </template>
        </el-table-column>
        <!-- <el-table-column prop="outId" label="订单外部id" align="center" /> -->
        <el-table-column prop="superId" label="订单上级id" align="center" />
        <el-table-column prop="createBy" label="推荐人名字" align="center" />
        <el-table-column prop="source" label="订单来源" align="center" />
        <el-table-column prop="superName" label="上级名" align="center" />
        <el-table-column prop="phone" label="手机号" align="center" />
        <el-table-column prop="stockId" label="存量套餐" :formatter="formatterCombo" align="center" />
        <el-table-column prop="type" label="类型" align="center" />
        <el-table-column prop="state.state" label="订单状态" align="center" />
        <el-table-column prop="result" label="结果描述" align="center" />
        <el-table-column prop="backStatus" label="下级回调状态" align="center" />
        <el-table-column prop="note" label="验证码" align="center" />
        <el-table-column prop="recorder" label="推广人" align="center" />
        <!-- <el-table-column fixed="right" label="操作" width="150" align="center">
          <template #default="scope">
            <el-button type="primary" text bg size="small" @click="handleUpdate(scope.row)">查看详情</el-button>
          </template>
        </el-table-column> -->
      </el-table>
      <!-- 分页器 -->
      <div class="pagination" style="margin-top: 20px">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :page-size="paginationData.pageSize"
          :total="paginationData.total"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- <el-dialog v-model="dialogVisible" @closed="resetForm" width="60%">
      <el-form ref="formRef" :model="formData" label-width="100px" label-position="left" :rules="rules">
        <el-form-item prop="id" label="一级分类">
          <el-input v-model="formData.id" placeholder="请输入" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
      </template>
    </el-dialog> -->
  </div>
</template>

<style lang="scss" scoped>
.expandBox {
  max-height: 80px;
  min-height: 80px;
  overflow: hidden;
  transition: max-height ease-in-out 0.2s;
}
.expandBox2 {
  min-height: 80px;
  overflow: hidden;
  transition: max-height ease-in-out 0.2s;
}
.footbox {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
}
.pagination {
  display: flex;
  justify-content: flex-end;
}
.spans {
  margin-left: 20px;
}
.Xjstate {
  color: #afadad;
  /* background: #e7e7e7; */
}
</style>
